package com.baidu.common.utils;

/**
 * DeviceInfo.java
 *
 * @author liujie11
 * 
 * @date 2011-3-24
 * 
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;

import com.baidu.common.net.APN;
import com.baidu.common.net.Server;

public class DeviceInfo {
    public static final int NETWORK_TYPE_WIFI = 0;
    public static final int NETWORK_TYPE_MOBILE = 1;
    
    private static DeviceInfo instance = null;
    
    public static DeviceInfo getInstance() {
        if (instance == null)
            instance = new DeviceInfo();
        return instance;
    }
    
    private String deviceId;
    private String macAddress;
    private int screenW, screenH;
    
    public int getScreenW() {
        return screenW;
    }
    
    public int getScreenH() {
        return screenH;
    }
    
    public void setScreenSize(int w, int h) {
        screenW = w;
        screenH = h;
    }
    
    public String getDeviceId(Context context) {
        String target = "";
        
        TelephonyManager telephonyManager = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            target = deviceId = telephonyManager.getDeviceId();
        }
        
        if (!isValidID(deviceId)) {
            deviceId = "";
            // get device mac address
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (wifi != null) {
                try {
                    WifiInfo info = wifi.getConnectionInfo();
                    if (info != null) {
                        target = macAddress = info.getMacAddress();
                        
                    }
                } catch (Exception e) {
                    macAddress = "";
                }
            } else {
                macAddress = "";
            }
            
            if (!isValidID(macAddress)) {
                macAddress = "";
                target = getLocalRandomString(context);
            }
        }
        
        return target;
    }
    
    private int networkState;
    
    /**
     * 获得运营商的名称
     * 
     * @return
     */
    public String getOperatorName(Context context) {
        if (context != null) {
            TelephonyManager fg = (TelephonyManager) context
                .getSystemService(Activity.TELEPHONY_SERVICE);
            String imsi = fg.getSimOperator();
            // String name = fg.getSimOperatorName();// .getSimOperator();
            
            if (Tools.isEmpty(imsi)) {
                return "unkown";
            } else if (imsi.startsWith("46000") || imsi.startsWith("46002"))
                return "移动";// 中国移动
            else if (imsi.startsWith("46001"))
                return "联通";// 中国联通
            else if (imsi.startsWith("46003"))
                return "电信";// 中国电信
        }
        return "";
    }
    
    public int getNetworkState(Context context) {
        if (context != null) {
            ConnectivityManager conManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifiInfo = conManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (wifiInfo.getState() == NetworkInfo.State.CONNECTED
                || wifiInfo.getState() == NetworkInfo.State.CONNECTING) {
                networkState = NETWORK_TYPE_WIFI;
            } else {
                networkState = NETWORK_TYPE_MOBILE;
            }
        }
        return networkState;
    }
    
    public boolean isWifiConnected(Context context) {
        return getNetworkState(context) == NETWORK_TYPE_WIFI;
    }
    
    public boolean isNetworkAvaible(Context context) {
        State mobile = null;
        State wifi = null;
        try {
            ConnectivityManager manager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
            // mobile 3G Data Network
            mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
            // wifi
            wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        } catch (Exception e) {
            // TODO: handle exception
        }
        
        // 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
        if (mobile == State.CONNECTED)// || mobile == State.CONNECTING)
            return true;
        if (wifi == State.CONNECTED)// || wifi == State.CONNECTING)
            return true;
        
        return false;
    }
    
    public APN getApn(Context context) {
        Cursor cursor = null;
        APN tempApn = null;
        try {
            tempApn = new APN();
            cursor = context.getContentResolver().query(
                Uri.parse("content://telephony/carriers/preferapn"),
                new String[] { "name", "apn", "proxy ", "port" }, "current=1", null, null);
            if (cursor != null) {
                int count = cursor.getCount();
                cursor.moveToFirst();
                for (int i = 0; i < count; i++) {
                    String name = cursor.getString(0);
                    tempApn.setName(name);
                    String apnType = cursor.getString(1);
                    tempApn.setApnType(apnType);
                    String proxy = cursor.getString(2);
                    String port = cursor.getString(3);
                    tempApn.setProxyServer(new Server(proxy, port));
                    cursor.moveToNext();
                }
            }
            
        } catch (Exception e) {
        } finally {
            cursor.close();
        }
        
        return tempApn;
    }
    
    public boolean isWapApn(Context context) {
        if (!isWifiConnected(context)) {
            try {
                APN tempApn = this.getApn(context);
                if (Tools.isEmpty(tempApn.getApnType())) {
                    Server proxy = tempApn.getProxyServer();
                    if (proxy != null && !Tools.isEmpty(proxy.getAddress())) {
                        return true;
                    }
                } else if (tempApn.getApnType().contains("wap")) {
                    return true;
                }
            } catch (RuntimeException e) {
            } catch (Exception e) {
            }
        }
        return false;
    }
    
    public static boolean isPushSupported() {
        int sdkLevel = Build.VERSION.SDK_INT;
        if (sdkLevel >= 8) {
            return true;
        }
        return false;
    }
    
    /**
     * 
     * 是否支持C2DM推送
     */
    public static boolean isC2DMSupported() {
        int sdkLevel = Build.VERSION.SDK_INT;
        if (sdkLevel >= 8) {
            return true;
        }
        return false;
    }
    
    /**
     * 计算sdcard上的剩余空间
     * 
     * @return 剩余byte
     */
    @Deprecated
    public static long freeSpaceOnSd() {
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long sdFreeByte = ((long) stat.getAvailableBlocks() * (long) stat.getBlockSize());
        return sdFreeByte;
    }
    
    public static boolean hasSdCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }
    
    public String getSDPath() {
        if (hasSdCard()) {
            return Environment.getExternalStorageDirectory().getPath();
        } else
            return null;
    }
    
    /**
     * 获得SDK号 ，比如 10
     */
    @Deprecated
    public String getSDKVersion() {
        String sdk = android.os.Build.VERSION.SDK;
        return sdk;
    }
    
    /**
     * 获得SDK号 ，比如 10
     */
    public int getSDKVersionInt() {
        int sdk = android.os.Build.VERSION.SDK_INT;
        return sdk;
    }
    
    /**
     * 获得系统版本号 比如2.3.6
     */
    public static String getSysVersion() {
        return android.os.Build.VERSION.RELEASE;
    }
    
    /**
     * 获得手机型号 ,比如 GT-9100
     */
    public static String getIMEInfo() {
        return android.os.Build.MODEL;
    }
    
    private boolean isValidID(String str) {
        if (str == null || str.length() < 10) {
            return false;
        }
        
        for (int i = 0; i < str.length(); i++)// 避免全0
        {
            if (str.charAt(i) != '0' && str.charAt(i) != ':') {
                return true;
            }
        }
        return false;
    }
    
    /**************************************************************************************/
    /** private methods **/
    
    private String getLocalRandomString(Context context) {
        String imei = "";
        File file = new File(getAppPath(true, context) + "imei");
        
        if (!file.exists()) {
            try {
                file.createNewFile();
                imei = getRandom();
                FileOutputStream out = new FileOutputStream(file);
                out.write(imei.getBytes("utf-8"));
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                FileInputStream in = new FileInputStream(file);
                byte[] data = new byte[33];
                int l = in.read(data);
                imei = new String(data, 0, l, "utf-8").trim();
                in.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                
            }
            
        }
        return imei;
    }
    
    // 返回一个33位的字符串 r+32位MD5码
    private String getRandom() {
        StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyz");
        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        int range = buffer.length();
        for (int i = 0; i < 32; i++) {
            sb.append(buffer.charAt(r.nextInt(range)));
        }
        return "r" + Tools.getMD5(System.currentTimeMillis() + sb.toString()).toLowerCase();
    }
    
    private String getAppPath(boolean firstSD, Context context) {
        if (firstSD) {
            String t = getSDPath();
            if (Tools.isEmpty(t)) {
                return t;
            }
        }
        
        if (context != null) {
            context.getFilesDir().getPath();
        }
        
        return null;
    }
}
